package com.xiaotao.http.core;

import com.xiaotao.http.controllers.FileAccess;
import com.xiaotao.http.core.annotation.WebController;
import com.xiaotao.http.core.interfaces.Controller;
import com.xiaotao.http.core.request.HttpRequest;
import com.xiaotao.http.core.response.HttpResponse;
import com.xiaotao.utils.ClassUtils;

import java.io.IOException;
import java.lang.annotation.Annotation;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;

public class Handler implements Runnable{
    private static FileAccess fa = new FileAccess();
    private Socket socket;
    private static HashMap<String, Controller> routeMap = new HashMap<>();
    static {
        registerRoute();
    }
    public Handler(Socket socket) {
        this.socket = socket;
    }

    // 路由注册
    protected static void registerRoute() {
        List<String> classes = ClassUtils.scanClass("com.xiaotao");
        classes.forEach(className -> {
            try {
                Class clazz = Class.forName(className);
                Annotation[] annotations = clazz.getAnnotations();
                for (Annotation annotation : annotations) {
                    if (annotation instanceof WebController) {
                        WebController webController = (WebController) annotation;
                        routeMap.put(webController.value(), (Controller) clazz.newInstance());
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    @Override
    public void run() {
        try {
            // 先整个请求和响应类，请求报文的解析在请求类中完成
            HttpRequest request = new HttpRequest(socket);
            HttpResponse response = new HttpResponse(socket);
            // 根据URL取出匹配的控制器
            Controller controller = routeMap.get(request.getURI());
            if (controller == null ) {
                // 访问未注册的路由时的默认控制器
                fa.service(request, response);
            } else {
                // 调用注册的控制器
                controller.service(request, response);
            }
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
